<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\Controller;
use App\Models\Renting;
use App\severces\CurlSeverce;
use App\severces\JwtSeverce;
use App\severces\SmsSeverce;
use App\severces\WechaSeverce;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use function Sodium\increment;


class LoginController extends BaseController
{
    /**
     * 验证登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
       $params = $request->all();

        $validator = Validator::make($params, [
            'username' => 'required',
            'password' => 'required',
        ],[
            'username.required'=>'用户名不能为空',
            'password.required'=>'密码不能为空',
        ]);
        //验证表单是否通过
        if($validator->fails()){
            $error = $validator->errors();
            //判断是否是数组
            if(!is_array($error)){
                $error = $error->toArray();
            }
            $errorArr=[];
            foreach ($error as $key=>$val){
                $errorArr[] = $key . ':' . $val[0];
            }
            return $this->witejson(1001,null,$errorArr);
        }
        //验证对象是否登录成功
        $bool = auth()->guard('apiweb')->attempt($params);

        if($bool){
            //获取当前用户对象
            $user = auth()->guard('apiweb')->user();
            //获取登录生成的token
            $accessToken = $user->createToken('api')->accessToken;

            return $this->witejson(
                0,
                [
                    'accesstoken'=>$accessToken,
                    'expirce'=>7200
                ],
                '登录成功'
            );
        }
        return $this->witejson(1002,null,'登录失败');
    }


    /**
     * 发送验证码
     */
    public function sendSms()
    {
        try {
            $phone = '';
            $content = '短信验证码 : ' ;
            $code = rand(1000,9999);
            $content = $content .$code;
            $smsdata = SmsSeverce::sendSms($phone,$content);

            $sendCodeName= 'sendCodeName' . $phone;
            $sendTimeName = 'sendTimeName' .$phone;
            $sendCountName = 'sendCountName' .$phone . '_'. date('Ymd');
            dd($sendCountName);
            //判断发送时间 （发送频繁）

            //判断发送次数 （每天最多发多少次）

            if($smsdata['error_code'] == 0 ){
                cache()->set($sendCodeName,$code,600);
                cache()->set($sendTimeName,time(),30);
                cache()->increment($sendCountName);

                return $this->witejson(0,$code,'发送成功');
            }
        }catch (\Exception $e){
            return $this->witejson(10001,null,$e->getMessage());
        }



    }


    /**
     * 微信小程序登录，获取token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wxlogin(Request $request)
    {
        try {
            //参数校验
            $params = $this->validateParams($request->post(),[
               'code'=>'required'
            ]);

            $code = $params['code'];
            //获取openid
            $getArr = WechaSeverce::getOpenId($code);

            if(isset($getArr['errcode'])){
                abort(101,$getArr['errmsg']);
            }

            $rent = Renting::where('openid',$getArr['openid'])->first();

            if($rent){
                $rent->session_key = $getArr['session_key'];
                $rent->updated_at = time();
                $rent->save();

                $token = JwtSeverce::jwtEncode($rent->id);

            }else{
                $res = Renting::create($getArr);

                $token = JwtSeverce::jwtEncode($res->id);
            }

            return $this->witejson(0,$token,'登录成功');


        }catch (\Exception $e){
            return $this->witejson($getArr['errcode'],null,$e->getMessage());
        }

    }


}
